package com.boolib.shopadmin.config.shiro.commons;



import com.boolib.shopadmin.config.shiro.realm.MyRealm;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import java.util.Set;


@Slf4j
public class CacheReloadUtil {

    public static void reloadAuthorizing(MyRealm myRealm, String username){

        Subject subject = SecurityUtils.getSubject();

        String realmName = subject.getPrincipals().getRealmNames().iterator().next();
        //第一个参数为用户名,第二个参数为realmName,test想要操作权限的用户
        SimplePrincipalCollection principals = new SimplePrincipalCollection(username,realmName);

        subject.runAs(principals);

        Cache<Object, AuthenticationInfo> authenticationCache = myRealm.getAuthenticationCache();

        Cache<Object, AuthorizationInfo>  authorizationCache = myRealm.getAuthorizationCache();

        Set <Object > set0 =   authenticationCache.keys();

        log.info("移除前");



        log.info("认证");
        for (Object obj:set0) {

            log.info("key:"+obj.toString()+"----------------------value:"+authenticationCache.get(obj));
        }


        Set <Object > set = authorizationCache.keys();

        log.info("权限");
        for (Object obj:set) {

            log.info("key:"+obj.toString()+"----------------------value:"+authorizationCache.get(obj));
        }


        authenticationCache.remove(subject.getPrincipal().toString());

        //移除权限缓存
        authorizationCache.remove(subject.getPrincipals());



        log.info("移除后");
        set0 = authenticationCache.keys();

        set = authorizationCache.keys();

        log.info("认证");
        for (Object obj:set0) {
            log.info("key:"+obj.toString()+"----------------------value:"+authenticationCache.get(obj));
        }

        log.info("权限");
        for (Object obj:set) {

            log.info("key:"+obj.toString()+"----------------------value:"+authorizationCache.get(obj));
        }





        subject.releaseRunAs();
    }

}
